#include <windows.h>
#include "../common/common.h"

#pragma data_seg(".MGSHARE")

HWND hWndServer = NULL;
HHOOK hHook = NULL;
DWORD pidServer = NULL;
HINSTANCE hInstance = NULL;
BOOL authed = FALSE;

#pragma data_seg()
#pragma comment(linker, "/SECTION:.MGSHARE,RWS")


UINT	MG_KEYDOWN=0,
		MG_KEYUP=0,
		MG_LBUTTONDOWN=0,
		MG_LBUTTONUP=0,
		MG_LBUTTONDBLCLK=0,
		MG_RBUTTONDOWN=0,
		MG_RBUTTONUP=0,
		MG_RBUTTONDBLCLK=0,
		MG_TERMINATE=0,
		MG_NOTHING=0;


LRESULT CALLBACK hookProc(int, DWORD, DWORD);


/*** Export Function ********************************************************************
	Setup
	Remove
**/

EXTERN_C __declspec(dllexport)
BOOL Setup()
{
	if(hHook == NULL){
		hHook = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)hookProc, hInstance, NULL);
		if(hHook == NULL) {
			MessageBox(NULL, "Error!", NULL, NULL);
			return FALSE;
		}
	}
	authed = FALSE;
	return TRUE;
}

EXTERN_C __declspec(dllexport)
BOOL Remove()
{
	BOOL ret = NULL;
	if(hHook) {
		ret = UnhookWindowsHookEx(hHook);
		hHook = NULL;
	}
	else{
		return FALSE;
	}

	return ret;
}

EXTERN_C __declspec(dllexport)
void SetPID(DWORD processID)
{
	pidServer = processID;
}

EXTERN_C __declspec(dllexport)
void SetHWND(HWND hWnd)
{
	hWndServer = hWnd;
}

EXTERN_C __declspec(dllexport)
void SetAuth(BOOL auth)
{
	authed = auth;
}
/*** Export Function End **********************************************************************/

LRESULT CALLBACK hookProc(int code, DWORD wParam, DWORD lParam)
{
	if(code >= 0) {
		PMSG pMsg = (PMSG)lParam;
		DWORD pid = GetCurrentProcessId();
		if(authed == FALSE && pidServer && hWndServer && pid != pidServer) {
			switch(pMsg->message) {
			case WM_KEYDOWN:
			case WM_KEYUP:
			case WM_LBUTTONDOWN:
			case WM_LBUTTONUP:
			case WM_LBUTTONDBLCLK:
			case WM_RBUTTONDOWN:
			case WM_RBUTTONUP:
			case WM_RBUTTONDBLCLK:
//				PostMessage(HWND_BROADCAST, MSG_RBUTTONDBLCLK, pMsg->wParam, pMsg->lParam);
				pMsg->message = MSG_NOTHING;
				break;
			}
		}
	}
	return CallNextHookEx(hHook, code, wParam, lParam);
}

BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
	switch(dwReason) {
	case DLL_PROCESS_ATTACH:
		hInstance = (HINSTANCE)hModule;
		break;
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}